"""
上下文协议允许创建可用于with语句的上下文管理器
"""

import logging

logger = logging.getLogger(__name__)

class FileHandler:

    def __init__(self, file_name, mode, encoding='utf8'):
        self.file_name = file_name
        self.mode = mode
        self.encoding = encoding
        self.file = None

    def __enter__(self):
        """
        在进入代码块之前被调用，用于执行一些准备操作
        可以返回一个值，该值将被赋给as关键字之后的变量
        """
        self.file = open(self.file_name, self.mode, encoding=self.encoding)
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            logger.error(f"出错：{exc_val}")
        if self.file:
            self.file.close()


file_handler = FileHandler('01-__new__和__del__.py', 'r')
with file_handler as file:
    context = file.read()
    print(context)
